﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text;
using PowerGuiVsx.Module.Objects;

namespace PowerGuiVsx.Module
{
    [Cmdlet(VerbsLifecycle.Start, "Project")]
    public class StartProjectCommand : PowerGuiVsxCommand
    {
        [Parameter(ValueFromPipeline = true)]
        public Project Project { get; set; }

        [Parameter]
        public string ComputerName { get; set; }

        [Parameter]
        [Credential]
        public PSCredential Credential { get; set; }

        [Parameter]
        public SwitchParameter StartDebugging { get; set; }

        protected override void ProcessRecord()
        {
            if (String.IsNullOrEmpty(ComputerName))
            {
                var process = Process.Start(Project.OutputFile.FullName);

                if (StartDebugging.IsPresent)
                {
                    DebugProcessCommand.AttachToProcess((int)process.Id);
                }
            }
            else
            {
                var path = String.Format(@"\\{0}\C$\Windows\Temp\{1}", ComputerName, Project.OutputFile.Name);

                try
                {
                    ProcessUtils.CopyFile(Project.OutputFile.FullName, path, ComputerName, Credential.UserName, Credential.Password.ConvertToUnsecureString());
                    var pid = ProcessUtils.StartRemoteProcess(path, ComputerName, Credential.UserName, Credential.Password);
                    DebugProcessCommand.AttachToProcess((int)pid, ComputerName);
                }
                catch (Exception ex)
                {
                    WriteError(ex);
                    return;
                }
            }
        }
    }
}
